package com.yanqu.road.server.manger;

import com.google.protobuf.InvalidProtocolBufferException;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.pb.monopoly.CrossMonopolyProto;
import com.yanqu.road.server.manger.activity.dafuweng.entiety.CollectEventResult;
import com.yanqu.road.server.manger.player.GamePlayerMgr;
import com.yanqu.road.server.manger.union.GameUnionActivityGroupMgr;
import com.yanqu.road.server.protocol.CrossProtocol;

import java.util.Map;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicLong;

public class CrossReqMgr {
    private static AtomicLong msgId = new AtomicLong(0);

    private static Map<Long, CompletableFuture<CollectEventResult>> completableFutureMap = new ConcurrentHashMap<>();


    public static long getNextMsgId() {
        return msgId.incrementAndGet();
    }

    public static CollectEventResult sendMsg(long userId, CrossMonopolyProto.CrossDfwCollectReqMsg.Builder msg, int activityId) {
        long id = getNextMsgId();
        msg.setMsgId(id);
        CompletableFuture<CollectEventResult> completableFuture = new CompletableFuture<>();
        completableFutureMap.put(msg.getMsgId(), completableFuture);
        try {
            int groupId = GameUnionActivityGroupMgr.getGroupId(activityId, userId);
            GamePlayerMgr.sendUnionActivityGroupPacket(CrossProtocol.C_CROSS_DA_FU_WENG_GET_UNION_COLLECT, msg, userId, activityId, groupId);
            CollectEventResult collectEventResult = completableFuture.get(3, TimeUnit.SECONDS);
            return collectEventResult;
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            completableFutureMap.remove(id);
            return new CollectEventResult();
        }
        return null;
    }

    public static void receiveMsg(YanQuMessage packet) {
        try {
            CrossMonopolyProto.CollectEventResultMsg msg = CrossMonopolyProto.CollectEventResultMsg.parseFrom(packet.getBytes());
            boolean canDoCollectEvent = msg.getCanDoCollectEvent();
            boolean recachReward = msg.getRecachReward();
            int newBattleSkillId = msg.getNewBattleSkillId();
            CollectEventResult result = new CollectEventResult();
            result.setCanDoCollectEvent(canDoCollectEvent);
            result.setUnionCollectReachReward(recachReward);
            result.setNewBattleSkillId(newBattleSkillId);
            long id = msg.getMsgId();
            CompletableFuture<CollectEventResult> future = completableFutureMap.get(id);
            if (future != null) {
                future.complete(result);
                completableFutureMap.remove(id);
            }
        } catch (InvalidProtocolBufferException e) {
            e.printStackTrace();
        }
    }

}
